import { store } from "../index";
import { defineStore } from "pinia";
import { ApiFieldsList } from "@/api/customerManage/setting";
import { cloneDeep } from "lodash-es";

import { routes } from "@/router/routes";
const { wsCache } = useCache();

export const useMenu = defineStore("useMenu", {
	state: () => ({
		updateFlag: false, //更新菜单
		addRouters: [], // 动态菜单
		routers: [],  // 所有菜单(动态菜单+本地固定菜单)
		cacheRoutes: wsCache.get("cacheRoutes") || [] //缓存的面包屑路由
	}),
	actions: {
		async generateRoutes() {
			try {
				if (!wsCache.get("ACCESS_TOKEN")) return;
				const roleList = await ApiFieldsList({ menuType: 0 });
				wsCache.set("menuId", roleList?.[0]?.id);
				roleList.forEach((i) => {
					i.path = `/customer/${i.id}`;
					i.meta = { title: i.name, icon: i.ico };
					i.component = () => import("@/views/customer/index/index.vue");
					i.label = i.name;
					i.mainType = 'customer';  // 主应用跳转去区分
				});
				this.addRouters = roleList;
				const arr = cloneDeep(routes);
				arr.forEach((i) => {
					if (i.name === "customerManagement") {
						i.children = [...i.children, ...roleList];
					}
				});
				this.routers = arr;
			} catch (error) {}
		},
		async addRoutes() {
			await this.generateRoutes();
			// for (const route of this.addRouters) {
				// router.addRoute("customerManagement", route); // 动态添加可访问路由表
			// }
		},
		async setUpdateFlag() {
			this.updateFlag = !this.updateFlag;
		},
		setRouteCache(to) {
			// 把录音跳转的地址存储起来，用于面包屑返回之前路由携带参数
			if (!Array.isArray(this.cacheRoutes)) return (this.cacheRoutes = []);
			const { name, meta, path } = to;
			const index = this.cacheRoutes.findIndex((item) => item.path === to.path);
			const params = {
				name,
				meta,
				path
			}
			if (index === -1) {
				this.cacheRoutes.push(params);
			}  else {
				this.cacheRoutes.splice(index, 1, params);
			}
			wsCache.set("cacheRoutes", this.cacheRoutes);
		},
		setPathMetaTitle(path, title) {
			const index = this.cacheRoutes.findIndex((item) => item.path === path);
			this.cacheRoutes[index].meta.title = title;
			wsCache.set("cacheRoutes", this.cacheRoutes);
		}
	}
});

export const useMenuWithOut = () => {
	return useMenu(store);
};
